package com.data
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.system.fscommand;
	
	import mx.collections.ArrayCollection;
	
	import spark.primitives.Line;

	public class CSVParser
	{
		private var fs:FileStream;
		public var attrs:Array; //Column names
		
		public function CSVParser()
		{
		}
		
		
		private function readLine():String {
			var str:String = "";
			while(true) {
				var temp:String = fs.readUTFBytes(1);
				//trace(temp + "\n");
				str += temp;
				if (temp == "\n" || temp == "")
					break;
			}
			return str;
		} 		
		
		public function parseString(content:String):Array
		{
	
			var csvArray:Array = new Array();
			
			var csvLines:Array = content.split(File.lineEnding);
			
			this.attrs = csvLines[0].split(",");
			
			csvLines.splice(0,1);
			
			trace("The # of lines is " + csvLines.length);
			
			for each(var s:String in csvLines) 
			{
				var lineItems:Array = s.split(",");
				var obj:Object = new Object();
				
				for (var i:int = 0; i < attrs.length; i++) 
				{
					obj[attrs[i]] = Number(lineItems[i]);
				}
				//trace (obj.death_id);
				//trace(String(obj.id) + " " + String(obj.daylight));
				csvArray.push(obj);
			}
			return csvArray;
		}
		
		public function parseFile(file:File):Array 
		{
			// Beware!!! There must not be a line ending at the end of the file.
			fs = new FileStream();
			fs.open(file, FileMode.READ);	
			trace (fs.bytesAvailable + " bytes available");
			var content:String = fs.readUTFBytes(fs.bytesAvailable);
			return parseString(content);
		}				
	}
}